package com.salt.controller;

import com.salt.common.Result;
import com.salt.entity.User;
import com.salt.service.UserService;
import com.salt.service.VerificationCodeService;
import com.salt.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final VerificationCodeService verificationCodeService;
    private final JwtUtil jwtUtil;
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<User> register(
        @RequestParam String mobile,
        @RequestParam String password,
        @RequestParam(required = false) String inviteCode,
        @RequestParam(required = false) String nickName
    ) {
        try {
            User user = userService.register(mobile, password, inviteCode, nickName);
            return Result.success(user);
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(
        @RequestParam String mobile,
        @RequestParam String password
    ) {
        try {
            User user = userService.login(mobile, password);
            
            // 生成token
            String token = jwtUtil.generateToken(user.getId(), user.getMobile());

            Map<String, Object> data = new HashMap<>();
            data.put("user", user);
            data.put("token", token);

            return Result.success(data);
        } catch (Exception e) {
            log.error("用户登录失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 发送验证码
     */
    @PostMapping("/send-code")
    public Result<Boolean> sendCode(@RequestParam String mobile) {
        try {
            boolean success = verificationCodeService.sendCode(mobile);
            if (!success) {
                return Result.error("验证码发送失败");
            }
            return Result.success(true);
        } catch (Exception e) {
            log.error("验证码发送失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 重置密码
     */
    @PostMapping("/reset-password")
    public Result<Boolean> resetPassword(
        @RequestParam String mobile,
        @RequestParam String code,
        @RequestParam String newPassword
    ) {
        try {
            // 验证验证码
            if (!verificationCodeService.verifyCode(mobile, code)) {
                return Result.error("验证码错误或已过期");
            }
            
            // 重置密码
            boolean success = userService.resetPassword(mobile, newPassword);
            if (!success) {
                return Result.error("密码重置失败");
            }
            return Result.success(true);
        } catch (Exception e) {
            log.error("密码重置失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        try {
            // 由于使用JWT，服务端不需要处理token
            // 前端需要清除本地存储的token
            return Result.success(null);
        } catch (Exception e) {
            log.error("退出登录失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/current")
    public Result<User> getCurrentUser(@RequestHeader("Authorization") String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error("未登录或token无效");
            }
            
            // 去掉Bearer 前缀
            token = token.substring(7);
            
            // 从token中获取用户ID
            Long userId = jwtUtil.parseUserId(token);
            if (userId == null) {
                return Result.error("token无效");
            }
            
            // 查询用户信息
            User user = userService.findById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 清除敏感信息
            user.setPassword(null);
            
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error(e.getMessage());
        }
    }
}